// pages/volunteer/recommend/index.js
const {
  voluntaryConfigCity,
  voluntaryTemplateDetail,
  voluntarySchoolGroup,
  voluntaryAdd,
  voluntaryBatchAdd,
  voluntaryUpdateSort,
  voluntaryUpdateSortList,
  voluntarydDelete,
  voluntaryTemplateDelete,
  voluntaryTemplateCopy
} = require('../../../api/ai')
const {
  decodeUserInfo
} = require('../../../api/login')

function isSort(arr) {
  var flag = false
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] < arr[j]) {
        flag = true
        break
      }
    }
  }
  return flag
}
const {
  majorList
} = require('../../../api/api')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bottomLift: getApp().globalData.bottomLift,
    chooseList: [],
    score: '',
    tabIndex: 0,
    list: [],
    checked_png: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/volunteer/analyse_checked.png',
    nochecked_png: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/volunteer/analyse_nochecked.png',
    isAnalyse: false,
    visible: false,
    title: '',
    content: '',
    orderDesc: false,
    subjectData: [{
      id: 1,
      value: '智能排序',
      key: 'desc'
    }, {
      id: 2,
      value: '志愿表导出',
      key: 'export'

    }, {
      id: 3,
      value: '智能填充',
      key: 'fill'

    }],
    more: false,
    listData: [{
      id: 1,
      value: '志愿列表',
      url: '/pages/users/voluntary/index'
    }, {
      id: 2,
      value: '订单中心',
      url: '/pages/users/order/index'
    }],
    setting: {
      height: '50rpx',
      bgColor: 'rgba(0,0,0,.5)',
      color: '#ffffff',
      fontSize: '24rpx',
      align: 'center',
      top: '310rpx',
      left: '490rpx',
      borderRadius: '10rpx',
      border: 'border-bottom:1rpx solid #fff',
      triangle: 'top'

    },
    setting2: {
      height: '80rpx',
      bgColor: 'rgba(0,0,0,.5)',
      color: '#ffffff',
      fontSize: '24rpx',
      align: 'center',
      top: '-180rpx',
      left: '-20rpx',
      borderRadius: '10rpx',
      contentHeight: '160rpx',
      triangle: 'bottom'
    },
    navList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    if (options.tempNo) {
      this.setData({
        tempNo: options.tempNo,
      })
    }
    if (options.params) {
      const params = JSON.parse(decodeURIComponent(options.params))
      this.setData({
        ...params
      })
    }
    await this.getVoluntarySchoolGroup()
    this.getVoluntaryTemplateDetail()
  },
  //模板详情
  async getVoluntaryTemplateDetail() {
    let {
      tempNo,
      id,
      tabIndex,
      navList,
      majorList
    } = this.data
    const {
      result
    } = await voluntaryTemplateDetail(id)
    if (!tabIndex) {
      const indexList = Object.keys(result.mapList).filter(e => result.mapList[e].length > 0)
      tabIndex = indexList.length > 0 ? indexList[0] : Object.keys(result.mapList)[0]
    }
    result.addVolunteerTemplate.secondSelectChar = result.addVolunteerTemplate.secondSelect.replaceAll(',', '/')
    this.setData({
      addVolunteerTemplate: result.addVolunteerTemplate,
      mapList: result.mapList,
      tabIndex,
    })
    this.syncDetail()
  },

  intelligence() {
    var that = this
    const {
      score,
      ranking,
      firstSelect,
      secondSelect,
      province,
      provinceId
    } = this.data
    const params = {
      firstSelect,
      secondSelect,
      score,
      ranking,
      province,
      provinceId
    }
    wx.navigateTo({
      url: '/pages/volunteer/intelligence/index?params=' + encodeURIComponent(JSON.stringify(params))
    })
  },
  syncDetail() {
    const {
      mapList,
      majorList,
      tabIndex
    } = this.data
    majorList.map(item => {
      // majorList
      item.list = []
      for (let i = 0; i < item.specialNum; i++) {
        item.list.push({
          speSort: i + 1,
          matchRate: 0
        })
      }
      mapList[tabIndex] && mapList[tabIndex].map(e => {
        if (e.list && e.list[0].sort == item.sort) {
          const list = e.list.filter(data => data.matchRate)
          list.sort((a, b) => {
            return a.matchRate - b.matchRate
          })
          item.title = item.name.replace(/[0-9]/ig, '')
          let matchCn= list[0].active == "chong" ? '冲' : list[0].active == "wen" ? '稳' : '保'
          let matchEn= list[0].active
          let matchRate= list[0].matchRate
          if (item.specialNum) {
            item.list.map((item1, i) => {
              e.list.map(item2 => {
                if (item1.speSort == item2.speSort) {
                  item.list[i] = item2
                }
              })
            })
            e.list = item.list
          }
          item = Object.assign(item, e,{matchRate,matchEn,matchCn,id:list[0].id})
          return item
        }
      })
    })
    this.setData({
      majorList,
      list: majorList
    })
  },
  changeDesc(e) {

  },
  async getVoluntarySchoolGroup() {
    const id = this.data.id
    const {
      result
    } = await voluntarySchoolGroup(id)
    const majorList = result
    const mode = result[0].specialNum > 0 ? 'batch' : 'single'
    const newList = majorList.filter((item) => {
      return item.checked == false
    })
    const majorIndex = newList.length > 0 ? parseInt(newList[0].sort) - 1 : 0
    this.setData({
      majorList,
      mode,
      majorIndex
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  async analyse(e) {
    const {
      addVolunteerTemplate,
      list
    } = this.data
    const {
      result
    } = await decodeUserInfo()
    if (result.vips.indexOf('svip') <= -1) {
      wx.navigateTo({
        url: '/pages/article/vip/index',
      })
      return
    }
    const arr = []
    list.map(e => {
      if (e.matchRate) {
        arr.push(e.matchRate)
      }
    })
    addVolunteerTemplate.orderStatus = !isSort(arr)
    if (arr.length <= 0) {
      wx.showToast({
        title: '暂无填报信息',
        icon: 'none',
      })
      return
    }
    wx.navigateTo({
      url: '/pages/volunteer/detail/index?params=' + encodeURIComponent(JSON.stringify(addVolunteerTemplate))
    })
    addVolunteerTemplate.isAnalyze = 1
    this.setData({
      addVolunteerTemplate
    })
  },
  async changeIndex(e) {
    const {
      index,
      type
    } = e.currentTarget.dataset
    if (index == this.data.currentIndex || index == this.data.tabIndex) return
    this.setData({
      [type]: index,
    })
    await this.getVoluntarySchoolGroup()
    this.syncDetail()
  },
  onReachBottom() {

  },
  async load() {
    await this.getVoluntarySchoolGroup()
    this.getVoluntaryTemplateDetail()
  },
  hideModal() {
    this.setData({
      more: false,
      orderDesc: false
    })
  },
  goto(e) {
    const {
      url
    } = e.currentTarget.dataset
    wx.navigateTo({
      url,
    })
  },
  toggle(e) {
    this.hideModal()
    const {
      value,
      key
    } = e.currentTarget.dataset
    this.setData({
      [key]: !value
    })
  },
  volunteerAdd() {
    const title = '新建志愿表'
    const content = '<div style="padding:0 45px">保存当前志愿表，新增并使用新的志愿表</div>'
    this.setData({
      title,
      content,
      type: 'add',
      visible: true,
    })

  },

  volunteerCopy() {
    const title = '复制志愿表'
    const content = '复制当前志愿表并编辑'
    this.setData({
      visible: true,
      title,
      content,
      type: 'copy'
    })
  },
  back(e) {
    const pages = getCurrentPages()
    const {
      type
    } = e.currentTarget.dataset
    const prevpage = pages[pages.length - 2]
    if (prevpage.route == 'pages/volunteer/select/index') {
      if (type) {
        prevpage.setData({
          useBatch: type
        })
      }
      wx.navigateBack({
        success: res => {
          prevpage.setData({
            pageNo: 1,
            list: []
          })
          prevpage.getVoluntarySchoolGroup();
          prevpage.getList();
        }
      })
      return
    }
    const {
      addVolunteerTemplate,
      tabIndex
    } = this.data
    const params = addVolunteerTemplate
    // params.currentRegions ={provinceId:addVolunteerTemplate.provinceId,province:addVolunteerTemplate.province}
    params.useBatch = tabIndex
    wx.navigateTo({
      url: '/pages/volunteer/select/index?params=' + encodeURIComponent(JSON.stringify(params))
    })
  },
  async confirm(e) {
    const value = e.detail ? e.detail.value : ''
    const {
      addVolunteerTemplate,
      type
    } = this.data
    if (!value && type == 'add') {
      const result = await voluntaryTemplateDelete(addVolunteerTemplate.id)
      await this.getVoluntarySchoolGroup()
      this.getVoluntaryTemplateDetail()
    }
    if (!value && type == 'copy') {
      const result = await voluntaryTemplateCopy(addVolunteerTemplate.id)
      wx.showToast({
        title: '复制成功',
      })
    }
    if (value && value.url) {
      wx.navigateTo({
        url: value.url,
      })
    }
    if (value && value.key) {
      const obj = value
      const {
        addVolunteerTemplate,
        majorList
      } = this.data
      obj['detail'] = addVolunteerTemplate
      obj['list'] = majorList
      this.setData({
        modalObj: obj,
        richModal: true
      })
    }

  },
  //专科切换顺序
  changeDesc(e) {
    const checkIndex = e.detail.current
    const redoindex = e.detail.value
    if (redoindex === checkIndex) return
    this.setData({
      checkIndex,
      redoindex
    })
    this.voluntaryUpdateSort()
  },
  delele(e) {
    const {
      range,
      index,
    } = e.currentTarget.dataset
    const _self = this
    wx.showModal({
      content: `是否确定删除${range.title+(index+1)}`,
      confirmText: '确定',
      success: async function (res) {
        if (res.confirm) {
          let id = range.list.filter(e => {
            return e.id
          })[0].id
          await voluntarydDelete(id)
          _self.load()
        }
      }
    })
  },



  //专科保存--填报
  rangeChange(e) {
    const index = e.detail.value
    const {
      majorList,
      currentValue
    } = this.data
    const sort = majorList[index].sort
    this.voluntaryAdd(sort)

  },
  async voluntaryAdd(sort, currentValue) {
    const params = {
      sort: sort
    }
    const result = await voluntaryAdd(params)
    wx.showToast({
      title: majorList[index].name + '填报成功',
      icon: 'none'
    })
  },
  openPicker(e) {
    const {
      index,
      type,
      redoindex
    } = e.currentTarget.dataset
    if (type) {
      this.setData({
        rangeVisible: true,
        majorIndex: index
      })
    } else {
      this.setData({
        checkIndex: index,
        redoindex,
      })
      if (redoindex === -1 || redoindex === this.data.majorList.length) return
      this.voluntaryUpdateSort()
    }
  },
  // 修改排序
  async voluntaryUpdateSort() {
    const {
      majorList,
      checkIndex,
      redoindex,
      id
    } = this.data
    const list = []
    majorList[checkIndex].list.map(e => {
      if (e.sort) {
        let obj = {
          sort: redoindex + 1,
          id: e.id
        }
        if (!majorList[checkIndex].specialNum) {
          obj.speSort = redoindex + 1
        }
        list.push(obj)
      }
    })
    if (majorList[redoindex]) {
      majorList[redoindex].list.map(e => {
        if (e.sort) {
          let obj = {
            sort: checkIndex + 1,
            id: e.id
          }
          if (!majorList[checkIndex].specialNum) {
            obj.speSort = checkIndex + 1
          }
          list.push(obj)
        }
      })
    }

    const parmas = {
      //  changeSort:checkIndex+1,
      //  newSort:redoindex+1,
      list,
      //  tempId:id
    }
    const result = await voluntaryUpdateSortList(parmas)
    await this.getVoluntarySchoolGroup()
    if (majorList[redoindex]) {
      const name = majorList[checkIndex].name
      const sort = majorList[checkIndex].sort
      majorList[checkIndex].name = majorList[redoindex].name
      majorList[checkIndex].sort = majorList[redoindex].sort
      majorList[redoindex].sort = sort
      majorList[redoindex].name = name
    }
    majorList[checkIndex] = majorList.splice(redoindex, 1, majorList[checkIndex])[0];
    this.setData({
      majorList,
      list: majorList
    })

  },
  openPlanModal(e) {
    const {
      index,
      value,
      item
    } = e.currentTarget.dataset
    const {
      provinceId,
      addVolunteerTemplate
    } = this.data
    let params = {}
    if (!value.active) {
      const list = item.list.filter(e => {
        return e.schoolId
      })
      list.sort((a, b) => {
        return b.matchRate - a.matchRate
      })
      params = list[0]
    } else {
      params = value
    }
    const schoolItem = {
      provinceId: provinceId,
      active: params.active,
      school: {},
      params: {},
      voluntarySpecialtyScore: {},
      schoolPlan:{},
    }
    schoolItem.school.id = params.schoolId
    schoolItem.school.name = params.schoolSgName
    schoolItem.school.logoUrl = item.schoolLogo
    schoolItem.schoolPlan.schoolSgId = params.schoolSgId
    schoolItem.voluntarySpecialtyScore.matchRate = params.matchRate
    schoolItem.voluntarySpecialtyScore.matchEn = params.active
    schoolItem.params.firstSelect = addVolunteerTemplate.firstSelect
    schoolItem.params.schoolName = params.schoolName 
    this.setData({
      planVisible: true,
      checkIndex: index,
      majorIndex: index,
      useBatch: this.data.tabIndex,
      schoolItem,
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '德道升学',
      path: '/pages/volunteer/index/index?scene=' + wx.getStorageSync('userInfo').id,
      imageUrl: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg'
    }
  },
  onUnload() {
    const pages = getCurrentPages()
    const prevpage = pages[pages.length - 2]
    prevpage.setData({
      pageNo: 1,
      list: []
    })
    if (prevpage.route == 'pages/volunteer/select/index') {
      prevpage.getVoluntarySchoolGroup();
    }
    if (prevpage.route != 'pages/volunteer/intelligence/index') {
      prevpage.getList();
    }
  }

})